#include "string.h"

/* @brief: set every byte to the same value
 * @param str: start address
 * @param c: the value to be set
 * @param n: size
 * @return: start address
 */
void *memset(void *str, int c, size_t n) {
	size_t i;
	char *p = (char *)str;
	for (i = 0; i < n; i++) {
		*p = (char)c;
		p++;
	}
	return str;
}

/* @brief: copy a string to another address
 * @param des: destination address
 * @param src: source address
 * @param n: size
 * @return: destination address
 */
void *memcpy(void *des, void *src, size_t n) {
	char *p1 = (char *)des;
	char *p2 = (char *)src;
	size_t i;
	for (i = 0; i < n; ++i) {
		*p1 = *p2;
		p1++;
		p2++;
	}
	return des;
}

/* @brief: compare two string
 * @param n: compared size
 * @return: return 0 if str1 equals to str2,
 * 	or the diff of the first different byte
 */
int memcmp(const void *str1, const void *str2, size_t n) {
	char *p1 = (char *)str1;
	char *p2 = (char *)str2;
	size_t i;
	for (i = 0; i < n; ++i) {
		if (*p1 != *p2) {
			return *p1 - *p2;
		}
		p1++;
		p2++;
	}
	return 0;
}

/* @brief: get string length
 * @param str: string
 * @return: length (not including '\0')
 */
size_t strlen(const char *str) {
	int i;
	for (i = 0; str[i] != '\0'; ++i);
	return i;
}

/* @brief: copy string from src to dest
 * @param dest: destination
 * @param src: source
 * @return: dest
 */
char *strcpy(char *dest, const char *src) {
	char *p1 = (char *)dest;
	char *p2 = (char *)src;
	while (*p2 != '\0') {
		*p1 = *p2;
		p1++;
		p2++;
	}
	*p1 = '\0';
	return dest;
}
